<template>
  <div>
    <!-- 三级联动表单 -->
    <el-form :inline="true" :model="formId" class="demo-form-inline">
      <el-form-item label="一级分类">
        <!-- v-mode收集的是option的value值 -->
        <el-select
          v-model="formId.category1Id"
          placeholder="一级分类"
          @change="handler1"
          :disabled="show"
        >
          <!-- 循环渲染数据 -->
          <el-option
            :label="c1.name"
            :value="c1.id"
            v-for="(c1, index1) in list1"
            :key="index1"
            >{{ c1.name }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select
          v-model="formId.category2Id"
          placeholder="二级分类"
          @change="handler2"
          :disabled="show"
        >
          <el-option
            :label="c2.name"
            :value="c2.id"
            v-for="(c2, index2) in list2"
            :key="index2"
            >{{ c2.name }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select
          v-model="formId.category3Id"
          placeholder="三级分类"
          @change="handler3"
          :disabled="show"
        >
          <el-option
            :label="c3.name"
            :value="c3.id"
            v-for="(c3, index3) in list3"
            :key="index3"
            >{{ c3.name }}</el-option
          >
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "CategorySelect",
  props: ["show"],
  data() {
    return {
      // 收集分类的id
      formId: {
        category1Id: "",
        category2Id: "",
        category3Id: "",
      },
      // 一级分类数据
      list1: [],
      // 二级分类数据
      list2: [],
      // 三级分类数据
      list3: [],
    };
  },
  mounted() {
    // 组件加载时获取一级分类的数据
    this.getCategory1List();
  },
  methods: {
    // 获取一级分类数据
    async getCategory1List() {
      const res = await this.$API.attr.reqCategory1List();
      if (res.code == 200) {
        this.list1 = res.data;
      }
    },
    // 获取二级分类数据
    async handler1() {
      // 清空二三级分类的数据和id
      this.list2 = [];
      this.list3 = [];
      this.formId.category2Id = "";
      this.formId.category3Id = "";
      const { category1Id } = this.formId;
      const res = await this.$API.attr.reqCategory2List(category1Id);
      if (res.code == 200) {
        this.list2 = res.data;
      }
      // this.$emit("getcategoryId", this.formId);
    },
    // 获取三级分类数据
    async handler2() {
      this.list3 = [];
      this.formId.category3Id = "";
      const { category2Id } = this.formId;
      const res = await this.$API.attr.reqCategory3List(category2Id);
      if (res.code == 200) {
        this.list3 = res.data;
      }
      // this.$emit("getcategoryId", this.formId);
    },
    // 触发获取商品列表的自定义事件
    async handler3() {
      this.$emit("getcategoryId", this.formId);
    },
  },
};
</script>

<style>
</style>